package com.ssm.controller;

import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.ssm.model.GradeModel;
import com.ssm.model.LoginInfo;
import com.ssm.model.TeacherModel;
import com.ssm.service.LoginService;
import com.ssm.service.MaterialService;
import com.ssm.service.ProfessorService;
import com.ssm.service.TeacherService;
import com.ssm.util.SftpUtil;

@Controller
@RequestMapping("/teacher")
public class TeacherController {
	//在线查看地址
	private static final String ONLINE_PREFIX = "http://ow365.cn/?i=14626&furl=";
	//头像地址
	private static final String HEAD_URL_PATH = "http://120.79.86.68:8080/upload/headUrl/";
	//材料地址
	private static final String MATERIAL_PATH = "http://120.79.86.68:8080/upload/materialFile/";
	
	@Autowired
	private TeacherService teacherService;
	@Autowired
	private LoginService loginService;
	@Autowired
	private MaterialService materialService;
	@Autowired
	private ProfessorService professorService;

	//首页
	/**
	 *  教师首页
	 * @param request 获得session中的用户信息
	 * @param model 封装前台显示信息-头像-Id-信息完整度
	 * @return 返回首页
	 */
	@RequestMapping("/index.do")
	public String showIndex(Model model,HttpServletRequest request){
		Subject subject = SecurityUtils.getSubject();
		LoginInfo loginInfo = (LoginInfo)subject.getPrincipal();
		Integer tId = loginInfo.getLoginId();
		TeacherModel teacherModel = teacherService.selectTeacherById(tId);
		request.getSession().setAttribute("sessionThead", teacherModel.gettHeadUrl());
		request.getSession().setAttribute("sessionTid", tId);
		request.getSession().setAttribute("sessionTinfo", teacherModel.gettInfo());
		model.addAttribute("teacher",teacherModel);
		return "teacher/index";
	}

	//维护个人信息
	/**
	 * 跳转到维护个人信息界面
	 * @param session 获取session中当前用户Id
	 * @param model 封装查询的用户信息
	 * @return 返回个人信息显示页面
	 */
	@RequestMapping(value = "/info.do",method = RequestMethod.GET)
	public String info(Model model,HttpSession session){
		Integer tId = (Integer)session.getAttribute("sessionTid");
		TeacherModel teacher = teacherService.selectTeacherById(tId);
		List<GradeModel> gradeModels = teacherService.selectGrades();
		model.addAttribute("gradeModels",gradeModels);
		model.addAttribute("teacher",teacher);
		return "teacher/info";
	}

	@InitBinder  
	public void initBinder(WebDataBinder binder) {  
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
		dateFormat.setLenient(false);  
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   //true:允许输入空值，false:不能为空值
	}
	//更新个人信息
	/**
	 * 更新个人信息
	 * @param imgFile 头像图片
	 * @param teacherModel 其余信息封装在对象中
	 * @param request
	 * @return 重定向至首页
	 * @throws Exception
	 */
	@RequestMapping(value = "/completeInfo.do")
	public String saveInfo(TeacherModel teacherModel,HttpServletRequest request,MultipartFile imgFile) throws Exception{
		if(!imgFile.isEmpty()){
			//操作用户id
			Subject subject = SecurityUtils.getSubject();
			Integer tId = (Integer) request.getSession().getAttribute("sessionTid");
			//文件名
			String fileName = imgFile.getOriginalFilename();
			//文件地址
			String headUrl = HEAD_URL_PATH + tId + "/" + fileName;
			//文件类型：头像
			Integer uploadType = 1;
			//上传源文件inputStream
			FileInputStream inputStream = (FileInputStream)imgFile.getInputStream();
			//使用sftp工具上传文件至服务器
			SftpUtil.uploadToService(inputStream, fileName, tId.toString(), uploadType);
			System.out.println("头像上传成功!");
			teacherModel.settHeadUrl(headUrl);
		}
		//上传完成后将用户信息更新到数据库
		//完善个人信息，tInfo==1
		teacherModel.settInfo(1);
		teacherService.updateInfo(teacherModel);
		return "redirect:index.do";
	}
	//安全中心
	/**
	 * 安全中心页面
	 * @return 返回安全中心显示页面
	 */
	@RequestMapping(value = "/security.do",method = RequestMethod.GET)
	public String security(){
		return "teacher/security";
	}
	//安全中心-重置密码
	/**
	 * 已登录用户充值密码
	 * @param model 获取操作用户的id重置密码
	 * @return 跳转至重置密码界面重置
	 */
	@RequestMapping("/resetPwd.do")
	public String resetPwd(Model model){
		Subject subject = SecurityUtils.getSubject();
		LoginInfo loginInfo = (LoginInfo)subject.getPrincipal();
		model.addAttribute("loginId",loginInfo.getLoginId());
		return "teacher/resetPwd";
	}
	
	//查看课程信息
	/**
	 * 教师查看自己的课程表
	 * @param session 获取当前教师Id
	 * @param model 封装课程表信息 格式是5个集合，分别表示每天课程的时间（第1、2、3、4、5节课）
	 * @return 返回课程显示页面
	 */
	@RequestMapping("/courseSchedule.do")
	public String checkCourse(Model model,HttpSession session){
		Integer tId = (Integer)session.getAttribute("sessionTid");
		model.addAttribute("tId",tId);
		//第一节课list
		List<Object> courseList1 = new ArrayList<Object>();
		//第二节课list
		List<Object> courseList2 = new ArrayList<Object>();
		//第三节课list
		List<Object> courseList3 = new ArrayList<Object>();
		//第四节课list
		List<Object> courseList4 = new ArrayList<Object>();
		//第五节课list
		List<Object> courseList5 = new ArrayList<Object>();
		//查询教师课程
		TeacherModel teacherModel = teacherService.selectCourseByTid(tId);
		List list = new ArrayList<>();
		if(teacherModel.getCourseModel()!=null){
			//得到课程安排
			String coursePlan = teacherModel.getCourseModel().getCoursePlan();
			//转换为map格式，提取合适的数据格式
			JSONObject jsonObject = JSONObject.parseObject(coursePlan);
			Map courseMap = (Map)jsonObject;
			list = (List) courseMap.get(tId);
			for (Object object : list) {
				Map dayMap = (Map)object;
				if(dayMap.get("ctime").equals("1")){
					//第一节课
					courseList1.add(dayMap);
				}else if(dayMap.get("ctime").equals("2")){
					//第二节课
					courseList2.add(dayMap);
				}else if(dayMap.get("ctime").equals("3")){
					//第三节课
					courseList3.add(dayMap);
				}else if(dayMap.get("ctime").equals("4")){
					//第四节课
					courseList4.add(dayMap);
				}else if(dayMap.get("ctime").equals("5")){
					//第五节课
					courseList5.add(dayMap);
				}
			}
		}
		model.addAttribute("tName",teacherModel.gettName());
		model.addAttribute("list",list);
		model.addAttribute("courseList1",courseList1);
		model.addAttribute("courseList2",courseList2);
		model.addAttribute("courseList3",courseList3);
		model.addAttribute("courseList4",courseList4);
		model.addAttribute("courseList5",courseList5);
		return "teacher/courseInfo";
	}
	
	//评估材料
	/**
	 *  评估材料页面
	 * @param request 获取当前用户Id
	 * @param model 获取材料列表，在用户信息完善的同时，使用材料参数向教师材料表中插入材料列表
	 * @return 返回显示
	 */
	@RequestMapping("/materialDetails.do")
	public String showMaterial(Model model,HttpServletRequest request){
		Integer tId = (Integer)request.getSession().getAttribute("sessionTid");
		List materialList = materialService.selectTeacherMaterial(tId);
		model.addAttribute("dataList",materialList);
		return "teacher/materialDetails";
	}
	//上传材料文件

	/**
	 * 上传材料文件
	 * @param mfile 材料文件
	 * @param fileType 材料分类-区别于之前的头像文件，返回文件地址
	 * @param request 获取yonghuID
	 * @return 上传完成重新加载页面重新显示
	 * @throws Exception
	 */
	@RequestMapping("/uploadFiles.do")
	public String uploadFiles(MultipartFile mfile,String fileType,HttpServletRequest request) throws Exception{
		//文件名
		String fileName = mfile.getOriginalFilename();
		System.out.println("fileName:::"+fileName);
		//操作用户id
		Subject subject = SecurityUtils.getSubject();
		Integer tId = (Integer) request.getSession().getAttribute("sessionTid");
		//文件上传地址:	http://120.79.86.68:8080/upload/materialFile/ 5009/a.docx
		String materialPath = MATERIAL_PATH + tId + "/" + fileName;
		//上传源文件inputStream
		FileInputStream inputStream = (FileInputStream)mfile.getInputStream();
		//文件类型
		Integer uploadType = 2;
		//使用sftp工具上传文件至服务器
		SftpUtil.uploadToService(inputStream, fileName, tId.toString(), uploadType);
		//持久化文件地址
		List materialList = materialService.selectTeacherMaterial(tId);
		for (Object object : materialList) {
			Map eachMap = (Map)object;
			if(eachMap.get("k").equals(fileType)){
				//替换地址
				eachMap.replace("v", materialPath);
				System.out.println("替换成功！");
				break;
			}else{
				System.out.println("替换失败");
			}
		}
		materialService.updateTeacherMaterial(tId, materialList);
		//文件名称
		return "forward:materialDetails.do";
	}
	//下载文件

	/**
	 * ajax下载材料文件
	 * @param filePath 获取文件在服务器上的地址，通过sftp下载至本地，返回地址：通过用户Id建立文件夹区分
	 * @return 返回操作结果信息以及下载后的本机地址，封装为json格式
	 */
	@ResponseBody
	@RequestMapping("/downloadFile.do")
	public Object downloadFile(String filePath){
		System.out.println("文件下载地址："+filePath);
		//使用sftp工具类从服务器上下载文件至本地
		String downPath = SftpUtil.downloadFile(filePath);
		HashMap map = new HashMap<>();
		map.put("success", true);
		map.put("downPath", downPath);
		return map;
	}
	//搜索教师总结
	/**
	 *  ajax加载教师总结
	 * @param request 获取教师Id
	 * @return 返回总结信息json，格式与材料项参数格式相似
	 */
	@ResponseBody
	@RequestMapping("/getSummary.do")
	public Object getSummary(HttpServletRequest request){
		Integer tId = (Integer)request.getSession().getAttribute("sessionTid");
		List list = materialService.selecTeacherSummaryByTid(tId);
		HashMap map = new HashMap<>();
		if(list!=null){
			for (Object object : list) {
				Map eachMap = new HashMap<>();
				eachMap = (Map)object;
				System.out.println("eachMap>>"+eachMap);
				if(eachMap.get("k").equals("课程总结")){
					map.put("success", true);
					map.put("courseSummary", eachMap.get("v"));
				}else if(eachMap.get("k").equals("工作总结")){
					map.put("success", true);
					map.put("jobSummary", eachMap.get("v"));
				}
			}			
		}else{
			map.put("success", false);			
		}
		System.out.println("list>>"+list);
		System.out.println("map>>"+map);
		return map;
	}
	
	//保存summary
	/**
	 * ajax保存summary‘
	 * @param request 用户Id
	 * @param summary 接受总结内容
	 * @param type 总结类型，-课程总结，-工作总结
	 * @return 返回操作信息
	 */
	@ResponseBody
	@RequestMapping("/saveSummary.do")
	public Object saveSummary(String summary,String type,HttpServletRequest request){
		Integer tId = (Integer)request.getSession().getAttribute("sessionTid");
		List list = materialService.selecTeacherSummaryByTid(tId);
		HashMap paramMap = new HashMap<>();
		//封装json数据格式
		HashMap bMap = new HashMap<>();
		List sList = new ArrayList<>();
		HashMap sMap1 = new HashMap<>();
		HashMap sMap2 = new HashMap<>();
		paramMap.put("tId", tId);
		if(list==null){//添加
			if("课程总结".equals(type)){
				sMap1.put("k", "工作总结");
				sMap1.put("v", "");
			}else{
				sMap1.put("k", "课程总结");
				sMap1.put("v", "");
			}
			sMap2.put("k", type);
			sMap2.put("v", summary);
			sList.add(sMap1);
			sList.add(sMap2);
			bMap.put("root", sList);
			paramMap.put("tsContent", JSONObject.toJSONString(bMap));
			materialService.insertTeacherSummaryByTid(paramMap);
		}else {
			for (Object object : list) {
				Map eachMap = new HashMap<>();
				eachMap = (Map)object;
				System.out.println("eachMap>>"+eachMap);
				if(type.equals(eachMap.get("k"))){
					eachMap.replace("v", summary);
				}
			}
			bMap.put("root", list);
			paramMap.put("tsContent", JSONObject.toJSONString(bMap));
			materialService.updateTeacherSummaryByTid(paramMap);
		}
		HashMap map = new HashMap<>();
		return map;
	}
	
	//评估进度
	/**
	 * 查看评估进度
	 * @param request 获取用户Id
	 * @param model 查询评估安排数据 -教师信息-专家信息-评估进度信息
	 * @return 返回进度显示页面
	 */
	@RequestMapping("/assessSchedule.do")
	public String showSchedule(Model model,HttpServletRequest request){
		Integer tId = (Integer)request.getSession().getAttribute("sessionTid");
		HashMap resultMap = teacherService.selectAssessByTid(tId);
		model.addAttribute("resultMap",resultMap);
		return "teacher/assessSchedule";
	}
	
	//评估结果
	/**
	 *  评估结果web端显示
	 * @param model 未实现
	 * @return 返回页面显示
	 */
	@RequestMapping("/assessResult.do")
	public String showResult(Model model){
		return "teacher/assessResult";
	}
	
}
